﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;

namespace Apex.ASPNETCore.GlobalException
{
    /// <summary>
    /// 全局异常处理：参数（模型验证失败）
    /// </summary>
    public static class GlobalValidationExtensions
    {
        /// <summary>
        /// 自定义 验证失败错误响应
        /// https://learn.microsoft.com/zh-cn/aspnet/core/web-api/handle-errors?view=aspnetcore-8.0#validation-failure-error-response
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static IMvcBuilder AddCustomValidation(this IMvcBuilder builder)
        {
            return builder.ConfigureApiBehaviorOptions(options =>
            {
                options.InvalidModelStateResponseFactory = context =>
                {
                    var error = context.ModelState
                            .Where(x => x.Value.Errors.Any())
                            .SelectMany(
                                x => x.Value.Errors, // 字典项的值部分，即错误列表
                                (parent, child) => new // parent：字典项，即键值对，child：每个错误信息
                                {
                                    Key = parent.Key,
                                    Error = child.ErrorMessage
                                }
                            );
                    var errorString = string.Join("; ", error.Select(e => $"{e.Key}: {e.Error}"));
                    var responseResult = GlobalResponseResultHelper.CreateErrorResponse(400, errorString);
                    return new BadRequestObjectResult(responseResult);
                };
            });
        }
    }

}
